<template>
  <div class="w-full h-full">
    <div class="w-full h-full">
      <div class="grid gap-y-10">
        <HeaderOptionsCartComponent
          v-model:platform="searchConditions.platform"
          @refresh="handleRefresh"
        />
        <SelectComponent
          v-model:selectValue="searchConditions.selectValue"
          :loading="searchLoading"
          @search="handleSearch"
        />
        <TabelComponent
          v-model:loading="tableLoading"
          :userInfo="userInfo"
          :total="total"
          :searchConditions="searchConditions"
          @handlePaginationChange="handlePaginationChange"
        />
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { onMounted, ref, watch } from 'vue'
import { SelectComponent, TabelComponent, HeaderOptionsCartComponent } from './components'
import type { DataSource, SearchConditions } from './types/types'
import { generateUserData } from '@/utils'

const searchConditions = ref<SearchConditions>({
  platform: 'douyin',
  selectValue: '',
  page: 1,
  page_size: 10,
})
const tableLoading = ref<boolean>(false)
const searchLoading = ref<boolean>(false)
const userInfo = ref<DataSource[]>([])
const total = ref<number>(0)

const getUserInfo = async () => {
  try {
    tableLoading.value = true
    const response = await generateUserData(searchConditions.value)
    console.log(response)
    userInfo.value = response.dataSource
    total.value = response.total
    tableLoading.value = false
  } catch (error) {
    console.log(error)
  }
}

// 重置搜索条件
const handleRefresh = async () => {
  await refresh()
  // 等待重置完成后，再获取数据
  getUserInfo()
}
// 搜索
const handleSearch = async () => {
  searchLoading.value = true
  await refresh()
  getUserInfo()
  searchLoading.value = false
}
const handlePaginationChange = (data: { page: number; page_size: number }) => {
  searchConditions.value.page = data.page
  searchConditions.value.page_size = data.page_size

  getUserInfo()
}
const refresh = (): Promise<void> => {
  return new Promise((resolve) => {
    searchConditions.value = {
      ...searchConditions.value,
      selectValue: '',
      page: 1,
      page_size: 10,
    }
    userInfo.value = []
    total.value = 0
    resolve()
  })
}
watch(
  () => searchConditions.value,
  (newVal) => {
    console.log('searchConditions changed:', newVal)
  },
  { deep: true },
)

onMounted(() => {
  getUserInfo()
})
</script>
<style lang="scss" scoped></style>
